package org.springleaf.core.mvc.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;

@SuppressWarnings({"unchecked"})
public class FormData {

	private Map<String,Object> params;

	public FormData(Map<String,Object> params) {
		this.params = params;
	}
	
	public FormData(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		Enumeration<String> enumeration = request.getParameterNames();
		while(enumeration.hasMoreElements()){
			String name = enumeration.nextElement();
			String [] values = request.getParameterValues(name);
			if(values != null && values.length > 0){
				if(values.length > 1){
					map.put(name, values);
				}else{
					map.put(name, values[0]);
				}
			}
		}
		this.params = map;
	}

	public Map<String,Object> getParams() {
		return params;
	}

	public <T>T get(String key){
		return (T)this.params.get(key);
	}
	
	/**
	 * 把Request中的参数赋值进指定的类型中
	 */
	public <T>T to(Class<T> classz){
		try {
			T obj = classz.newInstance();
			return this.to(obj);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/***
	 * 把Request中的参数赋值进对象中
	 */
	public <T>T to(Object obj){
		try {
			BeanUtils.populate(obj, this.params);
			return (T)obj;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
